// 主要JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化轮播图
    initCarousel();
    
    // 初始化导航栏
    initNavbar();
    
    // 初始化表单验证
    initFormValidation();
    
    // 初始化动画效果
    initAnimations();
});

// 初始化轮播图
function initCarousel() {
    const carousel = new bootstrap.Carousel(document.getElementById('mainCarousel'), {
        interval: 5000,
        ride: 'carousel'
    });
}

// 初始化导航栏
function initNavbar() {
    // 滚动时改变导航栏样式
    window.addEventListener('scroll', function() {
        const navbar = document.querySelector('.navbar');
        if (window.scrollY > 50) {
            navbar.classList.add('navbar-scrolled');
        } else {
            navbar.classList.remove('navbar-scrolled');
        }
    });
}

// 初始化表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('.needs-validation');
    
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
}

// 初始化动画效果
function initAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
            }
        });
    }, observerOptions);

    // 观察所有卡片元素
    document.querySelectorAll('.card').forEach(card => {
        observer.observe(card);
    });
}

// API调用工具函数
const api = {
    // 基础URL
    baseUrl: '/api',
    
    // GET请求
    async get(url) {
        try {
            const response = await fetch(this.baseUrl + url);
            return await response.json();
        } catch (error) {
            console.error('GET请求失败:', error);
            throw error;
        }
    },
    
    // POST请求
    async post(url, data) {
        try {
            const response = await fetch(this.baseUrl + url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + this.getToken()
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (error) {
            console.error('POST请求失败:', error);
            throw error;
        }
    },
    
    // PUT请求
    async put(url, data) {
        try {
            const response = await fetch(this.baseUrl + url, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + this.getToken()
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (error) {
            console.error('PUT请求失败:', error);
            throw error;
        }
    },
    
    // DELETE请求
    async delete(url) {
        try {
            const response = await fetch(this.baseUrl + url, {
                method: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + this.getToken()
                }
            });
            return await response.json();
        } catch (error) {
            console.error('DELETE请求失败:', error);
            throw error;
        }
    },
    
    // 获取Token
    getToken() {
        return localStorage.getItem('token');
    },
    
    // 设置Token
    setToken(token) {
        localStorage.setItem('token', token);
    },
    
    // 移除Token
    removeToken() {
        localStorage.removeItem('token');
    }
};

// 消息提示工具
const message = {
    success(msg) {
        this.showToast('success', msg);
    },
    
    error(msg) {
        this.showToast('danger', msg);
    },
    
    warning(msg) {
        this.showToast('warning', msg);
    },
    
    info(msg) {
        this.showToast('info', msg);
    },
    
    showToast(type, msg) {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `toast align-items-center text-white bg-${type} border-0`;
        toast.setAttribute('role', 'alert');
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    ${msg}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;
        
        // 添加到页面
        const toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.appendChild(toast);
        document.body.appendChild(toastContainer);
        
        // 显示toast
        const bsToast = new bootstrap.Toast(toast);
        bsToast.show();
        
        // 自动移除
        toast.addEventListener('hidden.bs.toast', function() {
            document.body.removeChild(toastContainer);
        });
    }
};

// 日期格式化工具
const dateUtils = {
    format(date, format = 'YYYY-MM-DD HH:mm:ss') {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    },
    
    relative(date) {
        const now = new Date();
        const diff = now - new Date(date);
        const minutes = Math.floor(diff / 60000);
        const hours = Math.floor(diff / 3600000);
        const days = Math.floor(diff / 86400000);
        
        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;
        if (hours < 24) return `${hours}小时前`;
        if (days < 30) return `${days}天前`;
        
        return this.format(date, 'YYYY-MM-DD');
    }
};

// 表单验证工具
const validation = {
    required(value) {
        return value !== null && value !== undefined && value.trim() !== '';
    },
    
    email(value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(value);
    },
    
    phone(value) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(value);
    },
    
    minLength(value, length) {
        return value.length >= length;
    },
    
    maxLength(value, length) {
        return value.length <= length;
    }
};

// 文件上传工具
const fileUpload = {
    async upload(file, type = 'image') {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', type);
        
        try {
            const response = await fetch('/api/upload', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + api.getToken()
                },
                body: formData
            });
            
            const result = await response.json();
            if (result.code === 200) {
                return result.data;
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('文件上传失败:', error);
            throw error;
        }
    },
    
    validateImage(file) {
        const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
        const maxSize = 5 * 1024 * 1024; // 5MB
        
        if (!validTypes.includes(file.type)) {
            throw new Error('只支持JPG、PNG、GIF格式的图片');
        }
        
        if (file.size > maxSize) {
            throw new Error('图片大小不能超过5MB');
        }
        
        return true;
    }
};

// 导出工具函数
window.api = api;
window.message = message;
window.dateUtils = dateUtils;
window.validation = validation;
window.fileUpload = fileUpload;